package kioscodeal

import org.springframework.dao.DataIntegrityViolationException

import static org.springframework.http.HttpStatus.*
import grails.transaction.Transactional

@Transactional(readOnly = true)
class UserController {

    static allowedMethods = [save: "POST", update: "PUT", delete: "DELETE"]
	
	def scaffold = User
	
	def login = {}
	
	def beforeInterceptor = [action:this.&auth,
		except:["login", "authenticate", "logout","create","save","signup","success","confirm","edit", "cuenta"]]

	def auth() {
		if( !(session?.user?.role == Role.ADMINISTRATOR) ){
			flash.message = "Usted debe ser Administrador para realizar esta tarea."
			redirect(uri:'/')
			return false
		}
		else{
			return true
		}
	}
	@Transactional
	def signup() {
		def userInstance = new User(params)
		userInstance.estado=EstadoCliente.INACTIVO
		userInstance.confirmCode= UUID.randomUUID().toString()
		def comercioInstance = Comercio.findById(1)
		userInstance.localidad = comercioInstance.localidad
		if (!userInstance.save(flush: true)) {
            render(view: "create", model: [userInstance: userInstance])
            return
		}
	
		try {
			sendMail {
				to      "${userInstance.mail}"
				subject "KioscoDeal Confirmacion de Registro"
				html    g.render(template:'/email/registrationConfirmation',model:[user:userInstance])
			}

		} catch(Exception e) {
			log.error "Problem sending email $e.message", e
		}
	
		redirect(action: "success")
		render(view: "list", model: [userInstance: userInstance])

	}
	
	def success(){
		render(view:'/email/success', model: [message: 'Su cuenta ha sido creada. Por favor confirme sus datos ingresados. El link de confirmacion ha sido enviado a su cuenta de email']);
		redirect(uri:'/')
	}
	
	def confirm(String id){

		User userInstance= User.findByConfirmCode(id)
		if(!userInstance)
		{
			return;
		}

		userInstance.estado=EstadoCliente.ACTIVO
		if (!userInstance.save(flush: true)) {
			render(view: "/email/success", model: [message: 'Problema al activar la cuenta.'])
			return
		}
		else{
			render(view: "/email/success", model: [message: 'Su cuenta ha sido correctamente activada.'])
			redirect(action:"login")
		}
	}
	
	
	def authenticate = {
	  def user = User.findByLoginAndPassword(params.login, params.password)
	  if(user && user.estado==EstadoCliente.ACTIVO){
		session.user = user
		flash.message = "Hola ${user.nombre}!"
		redirect(uri:'/')
	  }else{
		flash.message = "Disculpe, ${params.login}. Por favor, verifique que su cuenta este activa e intentelo nuevamente."
		redirect(action:"login")
	  }
	}
	
	def logout = {
	  flash.message = "Adios ${session.user.login}"
	  session.user = null

	  redirect(uri:'/')
	}
	
    def index() {
        redirect(action: "list", params: params)
    }

    def list(Integer max) {
        params.max = Math.min(max ?: 10, 100)
        [userInstanceList: User.list(params), userInstanceTotal: User.count()]
    }

    def create() {
        [userInstance: new User(params)]

    }
	

	@Transactional
    def save() {
        def userInstance = new User(params)
		
        if (!userInstance.save(flush: true)) {
            render(view: "create", model: [userInstance: userInstance])
            return
        }
        flash.message = message(code: 'default.created.message', args: [message(code: 'user.label', default: 'User'), userInstance.id])
        redirect(action: "show", id: userInstance.id)
    }

    def show(Long id) {
        def userInstance = User.get(id)
        if (!userInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'user.label', default: 'User'), id])
            redirect(action: "list")
            return
        }

        [userInstance: userInstance]
    }

    def edit(User userInstance) {
        respond userInstance
    }
	
	@Transactional
     def update(User userInstance) {
        if (userInstance == null) {
            notFound()
            return
        }

        if (userInstance.hasErrors()) {
            respond userInstance.errors, view:'edit'
            return
        }

        userInstance.save flush:true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.updated.message', args: [message(code: 'User.label', default: 'User'), userInstance.id])
                redirect userInstance
            }
            '*'{ respond userInstance, [status: OK] }
        }
    }
	
    @Transactional
    def delete(User userInstance) {

        if (userInstance == null) {
            notFound()
            return
        }

        userInstance.delete flush:true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.deleted.message', args: [message(code: 'User.label', default: 'User'), userInstance.id])
                redirect action:"list", method:"GET"
            }
            '*'{ render status: NO_CONTENT }
        }
    }
	
	protected void notFound() {
		request.withFormat {
			form multipartForm {
				flash.message = message(code: 'default.not.found.message', args: [message(code: 'user.label', default: 'User'), params.id])
				redirect action: "list", method: "GET"
			}
			'*'{ render status: NOT_FOUND }
		}
	}
	
	def cuenta(){		
		render(view: "edit", model:[userInstance: session?.user])		
	}
}
